package cn.chencq.validator;

import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;

import cn.chencq.exception.MyException;

/**
 * 数据校验
 * 
 * @author chencq
 * @email chenchaoqun@incar100.com
 * @date 2017-04-23 15:50
 */
public class ValidatorUtils {
	private static Validator validator;

	static {
		validator = Validation.buildDefaultValidatorFactory().getValidator();
	}

	/**
	 * 校验对象
	 * 
	 * @param object
	 *            待校验对象
	 * @param groups
	 *            待校验的组
	 * @throws RRException
	 *             校验不通过，则报StaffServerException异常
	 */
	public static void validateEntity(Object object,
			Class<?>... groups) throws MyException {
		Set<ConstraintViolation<Object>> constraintViolations = validator
				.validate(object, groups);
		if (!constraintViolations.isEmpty()) {
			StringBuilder msg = new StringBuilder();
			for (ConstraintViolation<Object> constraint : constraintViolations) {
				msg.append(constraint.getMessage());
				break;// 只返回第一个校验不通过的信息
			}
			throw new MyException(msg.toString());
		}
	}
}
